<?php

namespace GuanChanghu\Library\Http\Middleware;

use GuanChanghu\Library\Facades\Client;
use GuanChanghu\Library\Facades\RSA;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use JsonException;

/**
 * Class RequestEncrypt
 * @tag encryption free
 * @package GuanChanghu\Library\Http\Middleware
 */
class ResponseEncrypt
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws JsonException
     */
    public function handle(Request $request, Closure $next): mixed
    {
        /**
         * @var JsonResponse $response
         */
        $response = $next($request);

        if (config('guan-changhu.encrypt.clients_encrypt_enable')[$request->route('client')]) {
            $response->setData($this->encrypt($response->getData(true)));
        }
        return $response;
    }

    /**
     * @param array $responseData
     * @return array
     * @throws JsonException
     */
    protected function encrypt(array $responseData): array
    {
        $client = Client::getClient();
        if (config('guan-changhu.encrypt.clients_encrypt_enable')[$client]) {
            return ['encrypted' => RSA::client('encrypt_' . $client)->encrypt(json_encode($responseData, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))];
        }

        return $responseData;
    }
}
